package com.jp.knowledge.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.KnowlageDetailActivity;
import com.jp.knowledge.adapter.KnowlageItemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.KnowlageData;
import com.jp.knowledge.model.SkillModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.FloatingItemDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 *知识餐 item
 */
public class KnowlageItemFragment extends BaseFragment implements ResultSubscriber.OnResultListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @ViewInject(R.id.refresh)
    protected CanRefreshLayout mRefresh;
    @ViewInject(R.id.can_content_view)
    private RecyclerView  listView;
    @ViewInject(R.id.comm_new_fragment_remind_bg)
    private LinearLayout  emptyLayout;

    private KnowlageItemAdapter adpter;
    private View mView;

    private  List<KnowlageData>   knowlageDatas ;
    private List<KnowlageData.GroupListBean>   listBean;

    private String typeId;
    private String date;
    private FileCacheManager fileManager;
    private String cachePath;

    public  KnowlageItemFragment newInstance(String typeId, String date){
        this.typeId = typeId;
        this.date = date;
        return  this;
    }

    public String getTypeId() {
        return typeId;
    }

    public String getDate() {
        return date;
    }

    public void setTypeId(String id){
        this.typeId = id;
        initCache();
    }

    public void setDate(String date){
        this.date = date;
        initCache();
    }

    public void refresh(){
        if(mContext != null)
            readCache();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(mView == null) {
            mView = inflater.inflate(R.layout.fragment_knowlage_item, container, false);
            x.view().inject(this, mView);
            init();
            readCache();
        }
        return mView;
    }

    @Override
    public void onDestroy() {
        wirteCache(knowlageDatas);
        super.onDestroy();
    }

    private void init(){
        mRefresh.setRefreshEnabled(true);
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setOnRefreshListener(this);

        adpter = new KnowlageItemAdapter(mContext,null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        listView.setLayoutManager(layoutManager);
//        StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(adpter);
//        listView.addItemDecoration(headersDecor);
        listView.setAdapter(adpter);
        fileManager = new FileCacheManager();
        initCache();

        adpter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                int type = listBean.get(position).getPackageType();
                KnowlageData.GroupListBean  data = listBean.get(position);
               long startTime =  data.getStartTime();
                UserData userData = application.getUserData();
               int vip =  userData == null ? 0 : userData.getIsVip();
                if(System.currentTimeMillis()<startTime&&vip!=1){
                    ToasUtil.toast(mContext,"未到开放时间，暂不能查看!");
                    return;
                }
                if(data.getOnlyVip()==1&&vip!=1){//需要VIP会员才能查看
                    ToasUtil.toast(mContext,"本套餐只对VIP用户开放，请开通VIP!");
                    return;
                }
                if(type==26) {
                    Intent intent = new Intent(mContext, KnowlageDetailActivity.class);
                    intent.putExtra("id", listBean.get(position).getMainId());
                    intent.putExtra("packageId", listBean.get(position).getPackageId());
                    intent.putExtra("title", listBean.get(position).getPackageTitle());
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
                    intent.putExtra("id", data.getPackageId());
                    intent.putExtra("type", data.getPackageType());
                    intent.putExtra("linkTitle", data.getPackageTitle());
                    intent.putExtra("linkIcon", data.getPackageCover());
                    startActivity(intent);
                }
            }
        });

        if(knowlageDatas==null||knowlageDatas.size()==0) {
            showEmpty();
        }else{
            hideEmpty();
        }
    }

    /***
     * 初始化缓存数据
     */
    private void initCache() {
        if(mContext != null)
            cachePath = mContext.getCacheDir().getPath() + "/knowage_data_" + typeId + "_" + date + ".data";
    }

    public void autoRefresh(){
        mRefresh.autoRefresh();
    }
    private void showEmpty(){
        adpter.updataAdapter(null);
        emptyLayout.setVisibility(View.VISIBLE);
    }

    private void hideEmpty(){
        emptyLayout.setVisibility(View.GONE);
    }
    /***
     * 获取网络数据
     */
    private void getData(){
        JsonObject param = new JsonObject();
        param.addProperty("time", date);
        param.addProperty("navType", typeId);
        HttpHelper.getInstance(mContext).knowledgeList(param, 1, this);
    }
    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {
        mRefresh.refreshComplete();
    }

    @Override
    public void onError(int requestType) {
        mRefresh.refreshComplete();
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode()==0) {
            knowlageDatas = data.getList(KnowlageData.class);
            updateData();
            //缓存数据
//            wirteCache(knowlageDatas);
        }else {
            ToasUtil.toast(mContext,"获取数据失败");
        }
        L.i(""+data);
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<KnowlageData>>() {
            @Override
            public void call(Subscriber<? super List<KnowlageData>> subscriber) {
                List<KnowlageData> data = (List<KnowlageData>) fileManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<KnowlageData>>() {
            @Override
            public void onCompleted() {
                if(knowlageDatas == null || knowlageDatas.size() == 0)
                    mRefresh.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<KnowlageData> data) {
                knowlageDatas = data;
                updateData();
                onCompleted();
            }
        });
    }

    /***
     * 保存缓存
     * @param knowlageDatas
     */
    private void wirteCache(final  List<KnowlageData> knowlageDatas){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(knowlageDatas != null && knowlageDatas.size()>0)
                    fileManager.wirteObject(knowlageDatas, cachePath);
            }
        }).start();
    }


    private void updateData(){
        if(knowlageDatas!=null&&knowlageDatas.size()>0) {

            Map<Integer, String> map = new HashMap<>();
            int size = knowlageDatas.size();
            listBean = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                KnowlageData kn = knowlageDatas.get(i);
                map.put(listBean.size(), kn.getGroupName());
                listBean.addAll(kn.getGroupList());
            }
//            itemDecoration.setKeys(map);
            adpter.updataAdapter(listBean);
            if(listBean!=null&&listBean.size()>0){
                hideEmpty();
            }else {
                showEmpty();
            }
        }else{
            showEmpty();
        }
    }
    @Override
    public void onRefresh() {
            getData();
    }

    @Override
    public void onLoadMore() {

    }
}
